package com.newshub.business.controller;

import com.newshub.common.Result;
import com.newshub.business.entity.Users;
import com.newshub.business.dto.UserQueryDTO;
import com.newshub.business.dto.PageResult;
import com.newshub.business.service.UsersService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UsersService usersService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @BusinessLog(level = LogLevel.INFO, description = "用户登录")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");

            if (username == null || password == null) {
                return Result.error("用户名和密码不能为空");
            }

            // 根据用户名查找用户
            Users user = usersService.getByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 验证密码（明文密码校验）
            if (!password.equals(user.getPasswordHash())) {
                return Result.error("密码错误");
            }

            // 检查用户状态
            if (user.getStatus() != null && user.getStatus() != 1) {
                return Result.error("用户已被禁用");
            }

            // 更新登录信息
            user.setLastLoginTime(LocalDateTime.now());
            user.setLoginCount(user.getLoginCount() != null ? user.getLoginCount() + 1 : 1);
            usersService.updateLoginInfo(user.getId(), user.getLastLoginTime());

            // 构建返回的用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("email", user.getEmail());
            userInfo.put("role", user.getRole());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("status", user.getStatus());
            userInfo.put("lastLoginTime", user.getLastLoginTime());
            userInfo.put("loginCount", user.getLoginCount());

            return Result.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    @BusinessLog(level = LogLevel.INFO, description = "获取当前用户信息")
    public Result<Map<String, Object>> getCurrentUser(@RequestParam Integer userId) {
        try {
            Users user = usersService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 构建返回的用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("email", user.getEmail());
            userInfo.put("role", user.getRole());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("status", user.getStatus());
            userInfo.put("lastLoginTime", user.getLastLoginTime());
            userInfo.put("loginCount", user.getLoginCount());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());

            return Result.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    @BusinessLog(level = LogLevel.INFO, description = "用户退出登录")
    public Result<String> logout() {
        return Result.success("退出登录成功");
    }
    
    /**
     * 分页查询用户列表
     */
    @PostMapping("/page")
    @BusinessLog(level = LogLevel.INFO, description = "分页查询用户列表")
    public Result<PageResult<Users>> getUserPage(@RequestBody UserQueryDTO queryDTO) {
        try {
            // 参数验证
            if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1) {
                queryDTO.setPageNum(1);
            }
            if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1) {
                queryDTO.setPageSize(10);
            }
            
            // 计算偏移量
            int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
            
            // 查询数据
            List<Users> users = usersService.getUsersByPage(queryDTO, offset, queryDTO.getPageSize());
            long total = usersService.countUsersByPage(queryDTO);
            
            // 使用PageResult统一分页格式
            PageResult<Users> result = PageResult.of(queryDTO.getPageNum(), queryDTO.getPageSize(), total, users);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    @BusinessLog(level = LogLevel.INFO, description = "获取用户统计信息")
    public Result<Map<String, Object>> getUserStats() {
        try {
            Map<String, Object> stats = usersService.getUserStats();
            return Result.success(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加用户
     */
    @PostMapping("/add")
    @BusinessLog(level = LogLevel.INFO, description = "添加用户")
    public Result<String> addUser(@RequestBody Users user) {
        try {
            // 参数验证
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }
            
            if (user.getPasswordHash() == null || user.getPasswordHash().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 检查用户名是否重复
            if (usersService.existsByUsername(user.getUsername().trim())) {
                return Result.error("用户名已存在");
            }
            
            // 检查邮箱是否重复
            if (usersService.existsByEmail(user.getEmail().trim())) {
                return Result.error("邮箱已存在");
            }
            
            // 设置默认值
            if (user.getRole() == null) {
                user.setRole("user");
            }
            if (user.getStatus() == null) {
                user.setStatus(1);
            }
            
            // 添加用户
            boolean success = usersService.create(user);
            if (success) {
                return Result.success("添加用户成功");
            } else {
                return Result.error("添加用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    @BusinessLog(level = LogLevel.INFO, description = "更新用户信息")
    public Result<String> updateUser(@RequestBody Users user) {
        try {
            // 参数验证
            if (user.getId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }
            
            // 检查用户名是否重复（排除自己）
            Users existingUser = usersService.getByUsername(user.getUsername().trim());
            if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                return Result.error("用户名已存在");
            }
            
            // 检查邮箱是否重复（排除自己）
            existingUser = usersService.getByEmail(user.getEmail().trim());
            if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                return Result.error("邮箱已存在");
            }
            
            // 更新用户
            boolean success = usersService.update(user);
            if (success) {
                return Result.success("更新用户成功");
            } else {
                return Result.error("更新用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @BusinessLog(level = LogLevel.WARN, description = "删除用户")
    public Result<String> deleteUser(@PathVariable Integer id) {
        try {
            boolean success = usersService.delete(id);
            if (success) {
                return Result.success("删除用户成功");
            } else {
                return Result.error("删除用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除用户
     */
    @PostMapping("/delete/batch")
    @BusinessLog(level = LogLevel.WARN, description = "批量删除用户")
    public Result<String> deleteBatchUsers(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的用户");
            }
            
            boolean success = usersService.deleteBatchUsers(ids);
            if (success) {
                return Result.success("批量删除用户成功");
            } else {
                return Result.error("批量删除用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    @BusinessLog(level = LogLevel.INFO, description = "更新用户状态")
    public Result<String> updateUserStatus(@PathVariable Integer id, @RequestParam Integer status) {
        try {
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }
            
            boolean success = usersService.updateStatus(id, status);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("状态更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新用户状态
     */
    @PostMapping("/status/batch")
    @BusinessLog(level = LogLevel.INFO, description = "批量更新用户状态")
    public Result<String> updateBatchStatus(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> ids = (List<Integer>) request.get("ids");
            Integer status = (Integer) request.get("status");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的用户");
            }
            
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }
            
            boolean success = usersService.updateBatchStatus(ids, status);
            if (success) {
                return Result.success("批量状态更新成功");
            } else {
                return Result.error("批量状态更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量状态更新失败：" + e.getMessage());
        }
    }
}
